﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Globalization;

namespace VSM
{
    public partial class StockCount : System.Web.UI.Page
    {
        #region Fields
        public static DataTable dtContents;
        public static DataTable dtHeader;
        private static DataTable dtWhs;
        private static GeneralFunctions GF = null;
        private string TblHeaderName = "OIGN";
        private string TblLineName = "IGN1";
        private string CurrentPageUrl = "/Business/Inventory/GoodsReceipt.aspx";
        private string HeaderKeyName = "DocEntry";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session[Utils.AppConstants.ID_User] == null
                    || Session[Utils.AppConstants.Password] == null
                    || Session[Utils.AppConstants.ID_Dealer] == null)
                {
                    Response.Redirect("../../Login.aspx");
                }
                if (!IsPostBack)
                {
                    string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                    ClearScreen();

                    // Get Warehouse
                    dtWhs = GF.GetWarehouseByDealerDepartment(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), Utils.AppConstants.SALES);

                    String grptId = Request.QueryString["grpt_id"];
                    if (!String.IsNullOrEmpty(grptId))
                    {
                        LoadData(grptId, ConvertDocType.Get2String(DocType.GOODS_RECEIPT));
                        SetScreenStatus("Update");
                    }
                    else
                    {
                        LoadDefault();
                        SetScreenStatus("New");
                    }
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvGRPT.PageIndex = e.NewPageIndex;
            DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
            BindData(tblIGN1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
                if (tblIGN1 != null)
                {
                    DataRow[] rupdate = tblIGN1.Select("No=" + lblNo.Text );
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tblIGN1.Rows.Remove(rupdate[0]);
                    }
                    this.grvGRPT.EditIndex = -1;
                    BindData((DataTable)Session["IGN1Table"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                //
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Load Model
                DropDownList ddlModel = (DropDownList)e.Row.FindControl("ddlModel");
                Label lblModel = (Label)e.Row.FindControl("lblModel");
                if (ddlModel != null)
                {
                    ddlModel.DataSource = GF.GetModelList(dbType);
                    ddlModel.DataValueField = "Code";
                    ddlModel.DataTextField = "Name";
                    ddlModel.DataBind();
                    ddlModel.Items.Insert(0, "");
                    if (lblModel != null) ddlModel.SelectedValue = lblModel.Text;
                }
                // Load Product
                DropDownList ddlProduct = (DropDownList)e.Row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, lblModel.Text);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");
                    Label lblProduct = (Label)e.Row.FindControl("lblProduct");
                    if (lblProduct != null) ddlProduct.SelectedValue = lblProduct.Text;
                }
                // Load Color
                DropDownList ddlColor = (DropDownList)e.Row.FindControl("ddlColor");
                if (ddlColor != null)
                {
                    ddlColor.DataSource = GF.GetColorList(dbType);
                    ddlColor.DataValueField = "Code";
                    ddlColor.DataTextField = "Name";
                    ddlColor.DataBind();
                    ddlColor.Items.Insert(0, "");
                    Label lblColor = (Label)e.Row.FindControl("lblColor");
                    if (lblColor != null) ddlColor.SelectedValue = lblColor.Text;
                }

                // Load Whs
                DropDownList ddlWhs = (DropDownList)e.Row.FindControl("ddlWhs");
                if (ddlWhs != null)
                {
                    ddlWhs.DataSource = dtWhs;
                    ddlWhs.DataValueField = "WhsCode";
                    ddlWhs.DataTextField = "WhsName";
                    ddlWhs.DataBind();
                    HiddenField hdnWhsCode = (HiddenField)e.Row.FindControl("hdnWhsCode");
                    if (hdnWhsCode != null) ddlWhs.SelectedValue = hdnWhsCode.Value;
                }

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");

                DataTable tbIGN1 = (DataTable)Session["IGN1Table"];
                if (tbIGN1 != null)
                {
                    DataRow[] rupdate = tbIGN1.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["U_StockCountQty"] = GF.FormatNumeric(txtQuantity.Text, "QtyDec");
                        rupdate[0]["Quantity"] = GF.FormatNumeric(txtQuantity.Text, "QtyDec");
                        string lsSCQty = GF.FormatNumeric(txtQuantity.Text, "QtyDec");
                        int liSCQty = int.Parse(string.IsNullOrEmpty(lsSCQty) ? "0" : lsSCQty);

                        string lsOnHand = GF.FormatNumeric(GetOnHandQty(rupdate[0]["ItemCode"].ToString(), rupdate[0]["WhsCode"].ToString()), "QtyDec");
                        int liOnHand = int.Parse(string.IsNullOrEmpty(lsOnHand) ? "0" : lsOnHand);

                        rupdate[0]["OnHand"] = lsOnHand;
                        rupdate[0]["DiffQty"] = liOnHand - liSCQty;

                    }
                }

                this.grvGRPT.EditIndex = -1;

                BindData(tbIGN1);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void BindData(DataTable tblData)
        {
            Session["IGN1Table"] = tblData;
            this.grvGRPT.DataSource = tblData;
            this.grvGRPT.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblIGN1 != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        DataRow rowNew = tblIGN1.NewRow();
                                        rowNew["No"] = (tblIGN1.Rows.Count + 1).ToString();
                                        rowNew["ItemCode"] = item.Key;
                                        rowNew["Dscription"] = item.Value;
                                        rowNew["U_Model"] =
                                        rowNew["U_Product"] =
                                        rowNew["U_Color"] = string.Empty;
                                        rowNew["Quantity"] = 1;
                                        rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                                        

                                        //string lsSCQty = GF.FormatNumeric("1", "QtyDec");
                                        ///int liSCQty = int.Parse(string.IsNullOrEmpty(lsSCQty) ? "0" : lsSCQty);
                                        string lsOnHand = GF.FormatNumeric(GetOnHandQty(rowNew["ItemCode"].ToString(), rowNew["WhsCode"].ToString()), "QtyDec");
                                        int liOnHand = int.Parse(string.IsNullOrEmpty(lsOnHand) ? "0" : lsOnHand);

                                        rowNew["U_StockCountQty"] = liOnHand;
                                        rowNew["OnHand"] = lsOnHand;
                                        rowNew["DiffQty"] = 0;
                                        tblIGN1.Rows.Add(rowNew);
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblIGN1);
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string grptId = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            string StockCountID = ((HiddenField)rowDocList.FindControl("hdnStockCountID")).Value;
                            LoadData(StockCountID, doctype);
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvGRPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value.Equals("C") )
                {
                    TextBox txtQuantity = (TextBox)myRow.FindControl("txtOrderQuantity");
                    LinkButton lnkDelete = (LinkButton)myRow.FindControl("lnkDelete");
                    if (lnkDelete != null) lnkDelete.Enabled = false;
                    if (txtQuantity != null) lnkDelete.Enabled = false;
                    {
                        txtQuantity.ReadOnly = true;
                        txtQuantity.BackColor = System.Drawing.Color.Transparent;
                        txtQuantity.BorderStyle = BorderStyle.None;
                    }
                }
            }
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                Transaction ts = new Transaction();
                DataSet ds = null;
                //String requestXML = _collectData();
                BuildDataSC();

                hdnStockCount_ID.Value = Guid.NewGuid().ToString();
                String requestXMLGR = _collectDataGR();
                String requestXMLGS = _collectDataGS();

                if (requestXMLGR != string.Empty) 
                    ds = ts.CreateMarketingDocument(requestXMLGR, ConvertDocType.Get2String(DocType.GOODS_RECEIPT), txtDocNo.Text, false, dbType);

                if (requestXMLGS != string.Empty)
                    ds = ts.CreateMarketingDocument(requestXMLGS, ConvertDocType.Get2String(DocType.GOODS_ISSUE), txtDocNo.Text, false, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXMLGR;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
                Transaction ts = new Transaction();
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataSet ds = ts.CloseCancelDocument(ConvertDocType.Get2String(DocType.GOODS_RECEIPT), txtDocNo.Text, isClose, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("No");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("WhsCode");
            dt.Columns.Add("U_StockCountQty");
            //
            dt.Columns.Add("OnHand");
            dt.Columns.Add("DiffQty");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dt.Rows.Count + 1; //dr["No"];
                    row["LineNum"] = dr["LineNum"];
                    row["ItemCode"] = dr["ItemCode"];
                   
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Product"] = dr["U_Product"];
                    row["U_Color"] = dr["U_Color"];
                    row["UomCode"] = dr["UomCode"];
                    row["Quantity"] = GF.FormatNumeric(dr["Quantity"].ToString(), "QtyDec");
                    row["U_StockCountQty"] = GF.FormatNumeric(dr["U_StockCountQty"].ToString(), "QtyDec");
                    row["WhsCode"] = dr["WhsCode"];

                    string lsSCQty = GF.FormatNumeric(dr["U_StockCountQty"].ToString(), "QtyDec");
                    int liSCQty = int.Parse(string.IsNullOrEmpty(lsSCQty) ? "0" : lsSCQty);

                    string lsOnHand = GF.FormatNumeric(GetOnHandQty(dr["ItemCode"].ToString(), dr["WhsCode"].ToString()), "QtyDec");
                    int liOnHand = int.Parse(string.IsNullOrEmpty(lsOnHand) ? "0" : lsOnHand);
                    row["OnHand"] = lsOnHand;
                    row["DiffQty"] = liOnHand - liSCQty;

                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadDefault()
        {
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocNo.Text = string.Empty;
            
            dtContents = BuildContents(dtContents);
            BindData(dtContents);
        }

        protected void LoadData(String grptId, string NewDocType)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            //Transaction ts = new Transaction();
            //DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, grptId, dbType);

            //if (returnDoc == null) returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, "1", dbType); //grpoId = "1"; get default            

            //if (returnDoc == null || returnDoc.Tables.Count < 2)
            //{
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            //    return;
            //}

            string SQLCommandHeader = "SELECT TOP 1 * FROM ( ";
            SQLCommandHeader += " select DocEntry, DocDate, TaxDate, Comments, U_stockcount_id from OIGN ";
            SQLCommandHeader += "   where U_SOType = 0 and U_stockcount_id = '" + grptId + "' union ";
            SQLCommandHeader += " select DocEntry, DocDate, TaxDate, Comments, U_stockcount_id from OIGE ";
            SQLCommandHeader += "   where U_SOType = 0 and U_stockcount_id = '" + grptId + "' ) AS A ORDER BY DocEntry DESC ";

            dtHeader = GF.GetMasterListBySqlCommand(dbType, SQLCommandHeader);
            DataRow dr = dtHeader.Rows[0];
            txtDocNo.Text = dr["DocEntry"].ToString();
            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")) );
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")) );
            txtRemarks.Text = dr["Comments"].ToString();
            hdnStockCount_ID.Value = dr["U_stockcount_id"].ToString();
            SetScreenStatus("Close");

            string SQLCommandDetails = string.Empty;
            // Get Receipt ..
            SQLCommandDetails = "select 0 No, I1. * from OIGN I inner join IGN1 I1 on I.DocEntry = I1.DocEntry where I.U_SOType = 0 and I.U_stockcount_id = '" + grptId + "'";
            DataTable dtGR = GF.GetMasterListBySqlCommand(dbType, SQLCommandDetails);
            // Get Issue
            SQLCommandDetails = "select 0 No, I1. * from OIGE I inner join IGE1 I1 on I.DocEntry = I1.DocEntry where I.U_SOType = 0 and I.U_stockcount_id = '" + grptId + "'";
            DataTable dtGS = GF.GetMasterListBySqlCommand(dbType, SQLCommandDetails);
            foreach (DataRow drGS in dtGS.Rows)
            {
                dtGR.Rows.Add(drGS.ItemArray);
            }

            dtContents = BuildContents(dtGR);
            BindData(dtContents);
        }

        protected void ClearScreen()
        {
            dtContents = new DataTable(TblLineName);
            dtContents.Columns.Add("No");
            dtContents.Columns.Add("LineNum");
            dtContents.Columns.Add("ItemCode");
            dtContents.Columns.Add("Dscription");
            dtContents.Columns.Add("U_Model");
            dtContents.Columns.Add("U_Product");
            dtContents.Columns.Add("U_Color");
            dtContents.Columns.Add("UomCode");
            dtContents.Columns.Add("Quantity");
            dtContents.Columns.Add("U_StockCountQty");
            dtContents.Columns.Add("WhsCode");
            //
            dtContents.Columns.Add("OnHand");
            dtContents.Columns.Add("DiffQty");

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci); 

            txtDocNo.Text =
            txtRemarks.Text = String.Empty; 

            BindData(dtContents);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAddItems.Enabled =
                    btnAddAccessories.Enabled =
                    btnSave.Enabled = true;
                    btnCancel.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "O";
                    break;

                case "Update":
                    hdnIsUpdate.Value = "true";
                    btnAddItems.Enabled =
                    btnAddAccessories.Enabled =
                    btnSave.Enabled = 
                    btnCancel.Enabled = false;
                    hdnStatus.Value = "O";
                    break;

                case "Close":
                    btnAddItems.Enabled =
                    btnAddAccessories.Enabled =
                    btnSave.Enabled = 
                    btnCancel.Enabled = false;
                    hdnIsUpdate.Value = "false";
                    hdnStatus.Value = "C";
                    break;
            }
        }

        private void BuildSRNT(ref DataTable dtSRNT, string ItemCode, string SysNumber, string DistNumber, string InDate, string Notes,
            double Quantity, string WhsCode, string DocType, string DocEntry, string DocLineNum)
        {
            if (dtSRNT == null)
            {
                dtSRNT = new DataTable("SRNT");
                dtSRNT.Columns.Add("ItemCode");
                dtSRNT.Columns.Add("SysNumber");    // Default
                dtSRNT.Columns.Add("DistNumber");   // VIN Number
                dtSRNT.Columns.Add("InDate");       // Get default
                dtSRNT.Columns.Add("Quantity");     // 1
                dtSRNT.Columns.Add("WhsCode");      // Default
                dtSRNT.Columns.Add("DocType");      // 13
                dtSRNT.Columns.Add("DocEntry");     // Get from Incoming Payment No.
                dtSRNT.Columns.Add("DocLineNum");   // 1
                dtSRNT.Columns.Add("Notes");   // 
                //dtSRNT.Columns.Add("BSubLineNo");   // LineNo
            }

            DataRow drSRNT = dtSRNT.NewRow();
            drSRNT["ItemCode"] = ItemCode;      // INV1
            drSRNT["SysNumber"] = SysNumber;
            drSRNT["DistNumber"] = DistNumber;   // VIN Number
            drSRNT["InDate"] = Utils.AppConstants.ConvertToDate(InDate).ToString("yyyyMMdd");
            drSRNT["Quantity"] = Quantity;       // INV1
            drSRNT["WhsCode"] = WhsCode;         // INV1
            drSRNT["DocType"] = DocType;         // INV1
            drSRNT["DocEntry"] = DocEntry;       // INV1
            drSRNT["DocLineNum"] = DocLineNum;   // INV1
            drSRNT["Notes"] = Notes;
            //drSRNT["BSubLineNo"] = BSubLineNo; // INV1
            dtSRNT.Rows.Add(drSRNT);
        }

        public String _collectData()
        {
            try
            {
                DataSet ds = new DataSet("DS");
                dtContents = (DataTable)Session["IGN1Table"];
                DataTable dtHeader = new DataTable(TblHeaderName);

                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series");
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("Comments");
                // UDF
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_stockcount_id");
                DataRow drHeader = dtHeader.NewRow();
                // Add new
                drHeader["Series"] = 19;
                drHeader["DocStatus"] = "O";
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text.Trim();
                // UDF
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;
                drHeader["U_stockcount_id"] = hdnStockCount_ID.Value;

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("AcctCode");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("UomCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("U_StockCountQty");
                dt.Columns.Add("WhsCode");
                if (dtContents != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        DataRow row = dt.NewRow();
                        row["LineNum"] = liNo;
                        row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];
                        row["Dscription"] = dr["Dscription"];
                        row["AcctCode"] = "999999";
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["UomCode"] = dr["UomCode"];
                        row["Quantity"] = dr["Quantity"];
                        row["U_StockCountQty"] = dr["U_StockCountQty"];
                        row["WhsCode"] = dr["WhsCode"];

                        dt.Rows.Add(row);
                        liNo++;
                    }
                }
                ds.Tables.Add(dt.Copy());

                // Build VIN Number (Serial Number) datatable to save
                DataTable dtSRNT = (DataTable)Session["tblSRNT"];
                if (dtSRNT != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow[] rDocLineNum = dtSRNT.Select("ItemCode='" + dr["ItemCode"].ToString() + "'");
                        if (rDocLineNum.Length > 0)
                        {
                            for (int i = 0; i < rDocLineNum.Length; i++)
                            {
                                rDocLineNum[i]["DocLineNum"] = dr["LineNum"];
                                rDocLineNum[i]["WhsCode"] = dr["WhsCode"];
                            }
                        }
                    }
                    ds.Tables.Add(dtSRNT.Copy());
                }

                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS( ConvertDocType.Get2String(DocType.GOODS_RECEIPT), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return string.Empty;
            }
        }

        private void BuildDataSC()
        {
            DataTable dtSC = (DataTable)Session["IGN1Table"];
            DataTable dtGR = CreateGRDT();
            DataTable dtGS = CreateGSDT();

            foreach (DataRow dr in dtSC.Rows)
            {
                int liSCQty = int.Parse(string.IsNullOrEmpty(dr["U_StockCountQty"].ToString()) ? "0" : dr["U_StockCountQty"].ToString());
                string lsOnHandQty = GetOnHandQty(dr["ItemCode"].ToString(), dr["WhsCode"].ToString());
                int liOnHandQty = int.Parse(string.IsNullOrEmpty(lsOnHandQty) ? "0" : lsOnHandQty);
                // 
                if (liSCQty > liOnHandQty) // Goods Receipt ...
                {
                    DataRow rowGR = dtGR.NewRow();
                    rowGR["LineNum"] = dtGR.Rows.Count;
                    rowGR["LineStatus"] = "O";
                    rowGR["ItemCode"] = dr["ItemCode"];
                    rowGR["Dscription"] = dr["Dscription"];
                    rowGR["AcctCode"] = "999999";
                    rowGR["U_Model"] = dr["U_Model"];
                    rowGR["U_Product"] = dr["U_Product"];
                    rowGR["U_Color"] = dr["U_Color"];
                    rowGR["UomCode"] = dr["UomCode"];
                    rowGR["Quantity"] = liSCQty - liOnHandQty;
                    rowGR["U_StockCountQty"] = liSCQty;
                    rowGR["WhsCode"] = dr["WhsCode"];
                    dtGR.Rows.Add(rowGR);
                }
                else if (liSCQty < liOnHandQty) // Goods Issue ...
                {
                    DataRow rowGS = dtGS.NewRow();
                    rowGS["LineNum"] = dtGS.Rows.Count;
                    rowGS["LineStatus"] = "O";
                    rowGS["ItemCode"] = dr["ItemCode"];
                    rowGS["Dscription"] = dr["Dscription"];
                    rowGS["AcctCode"] = "999999";
                    rowGS["U_Model"] = dr["U_Model"];
                    rowGS["U_Product"] = dr["U_Product"];
                    rowGS["U_Color"] = dr["U_Color"];
                    rowGS["UomCode"] = dr["UomCode"];
                    rowGS["Quantity"] = Math.Abs(liSCQty - liOnHandQty);
                    rowGS["U_StockCountQty"] = liSCQty;
                    rowGS["WhsCode"] = dr["WhsCode"];
                    dtGS.Rows.Add(rowGS);
                }
            }
            Session["GRTable"] = dtGR;
            Session["GSTable"] = dtGS;
        }

        private string _collectDataGR()
        {
            try
            {
                DataSet ds = new DataSet("DS");
                //dtContents = (DataTable)Session["IGN1Table"];
                dtContents = (DataTable)Session["GRTable"];
                if (dtContents == null || dtContents.Rows.Count <= 0) return string.Empty;

                DataTable dtHeader = new DataTable(TblHeaderName);
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series");
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("Comments");
                // UDF
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_stockcount_id");
                dtHeader.Columns.Add("U_SOType");
                DataRow drHeader = dtHeader.NewRow();
                // Add new
                drHeader["Series"] = 19;
                drHeader["DocStatus"] = "O";
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text.Trim();
                // UDF
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;
                drHeader["U_stockcount_id"] = hdnStockCount_ID.Value;
                drHeader["U_SOType"] = 0; // Stock Count
                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = TblHeaderName;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable(TblLineName);
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("AcctCode");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("UomCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("U_StockCountQty");
                dt.Columns.Add("WhsCode");
                if (dtContents != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtContents.Rows)
                    {
                        DataRow row = dt.NewRow();
                        row["LineNum"] = liNo;
                        row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];
                        row["Dscription"] = dr["Dscription"];
                        row["AcctCode"] = "999999";
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["UomCode"] = dr["UomCode"];
                        row["Quantity"] = dr["Quantity"];
                        row["U_StockCountQty"] = dr["U_StockCountQty"];
                        row["WhsCode"] = dr["WhsCode"];
                        dt.Rows.Add(row);
                        liNo++;
                    }
                }

                ds.Tables.Add(dt.Copy());

                // Build VIN Number (Serial Number) datatable to save
                //DataTable dtSRNT = (DataTable)Session["tblSRNT"];
                //if (dtSRNT != null)
                //{
                //    foreach (DataRow dr in dt.Rows)
                //    {
                //        DataRow[] rDocLineNum = dtSRNT.Select("ItemCode='" + dr["ItemCode"].ToString() + "'");
                //        if (rDocLineNum.Length > 0)
                //        {
                //            for (int i = 0; i < rDocLineNum.Length; i++)
                //            {
                //                rDocLineNum[i]["DocLineNum"] = dr["LineNum"];
                //                rDocLineNum[i]["WhsCode"] = dr["WhsCode"];
                //            }
                //        }
                //    }
                //    ds.Tables.Add(dtSRNT.Copy());
                //}

                DocumentXML objInfo = new DocumentXML();
                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.GOODS_RECEIPT), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return string.Empty;
            }        
        }

        public String _collectDataGS()
        {
            try
            {
                DataTable dtGS = (DataTable)Session["GSTable"];
                if (dtGS == null || dtGS.Rows.Count <= 0) return string.Empty;

                DataTable dtHeader = new DataTable("OIGE");
                dtHeader.Columns.Add("DocEntry");
                dtHeader.Columns.Add("DocNum");
                dtHeader.Columns.Add("Series");
                dtHeader.Columns.Add("DocStatus");
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("Comments");
                // UDF
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_stockcount_id");
                dtHeader.Columns.Add("U_SOType");
                DataRow drHeader = dtHeader.NewRow();
                // Add new
                drHeader["Series"] = 20;
                drHeader["DocStatus"] = "O";
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text.Trim();
                // UDF
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.SALES;
                drHeader["U_stockcount_id"] = hdnStockCount_ID.Value;
                drHeader["U_SOType"] = 0; // Stock Count

                dtHeader.Rows.Add(drHeader);
                dtHeader.TableName = "OIGE";

                DataTable dt = new DataTable("IGE1");
                dt.Columns.Add("DocEntry");
                dt.Columns.Add("LineNum");
                dt.Columns.Add("LineStatus");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("AcctCode");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("U_Product");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("UomCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("U_StockCountQty");
                dt.Columns.Add("WhsCode");

                if (dtGS != null)
                {
                    int liNo = 0;
                    foreach (DataRow dr in dtGS.Rows)
                    {
                        DataRow row = dt.NewRow();
                        row["LineNum"] = liNo;
                        row["LineStatus"] = "O";
                        row["ItemCode"] = dr["ItemCode"];
                        row["Dscription"] = dr["Dscription"];
                        row["AcctCode"] = "999999";
                        row["U_Model"] = dr["U_Model"];
                        row["U_Product"] = dr["U_Product"];
                        row["U_Color"] = dr["U_Color"];
                        row["UomCode"] = dr["UomCode"];
                        row["Quantity"] = dr["Quantity"];
                        row["U_StockCountQty"] = dr["U_StockCountQty"];
                        row["WhsCode"] = dr["WhsCode"];

                        dt.Rows.Add(row);
                        liNo++;
                    }
                }

                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                ds.Tables.Add(dtHeader.Copy());

                ds.Tables.Add(dt.Copy());

                return objInfo.ToXMLStringFromDS(ConvertDocType.Get2String(DocType.GOODS_ISSUE), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return string.Empty;
            }
        }

        private DataTable CreateGRDT()
        {
            DataTable dt = new DataTable(TblLineName);
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("LineStatus");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("AcctCode");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("U_StockCountQty");
            dt.Columns.Add("WhsCode");
            return dt;
        }

        private DataTable CreateGSDT()
        {
            DataTable dt = new DataTable("IGE1");
            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("LineStatus");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("AcctCode");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Product");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("UomCode");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("U_StockCountQty");
            dt.Columns.Add("WhsCode");
            return dt;
        }

        private string GetOnHandQty(string ItemCode, string WhsCode)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());

            string lsSqlCommand = "select isNull(OnHand, 0) As OnHand From OITW where ItemCode = '" + ItemCode + "' and WhsCode = '" + WhsCode + "' ";
            return GF.GetSingleValue(dbType, lsSqlCommand, "OnHand");
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsGRPONo = fGetDefault.GetMaxDocEntry
            (
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER, // dbType
                Session[Utils.AppConstants.ID_Dealer].ToString(), 
                Utils.AppConstants.SALES,
                ConvertDocType.Get2String(DocType.GOODS_RECEIPT), 
                TblHeaderName, HeaderKeyName
            );
            if (txtDocNo.Text.CompareTo(lsGRPONo) != 0)
                Response.Redirect(CurrentPageUrl + "?grpt_id=" + lsGRPONo);
        }

        protected void ddlModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
                if (ddlModel.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Model');", true);
                    ddlModel.Focus();
                    return;
                }
                Label lblModel = (Label)row.FindControl("lblModel");
                lblModel.Text = ddlModel.SelectedValue;

                // Load Product
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct != null)
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    ddlProduct.DataSource = GF.GetProductByModel(dbType, ddlModel.SelectedValue);
                    ddlProduct.DataValueField = "Code";
                    ddlProduct.DataTextField = "Name";
                    ddlProduct.DataBind();
                    ddlProduct.Items.Insert(0, "");

                    Label lblProduct = (Label)row.FindControl("lblProduct");
                    lblProduct.Text = ddlProduct.SelectedValue;
                    SetItem(row);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
                if (ddlProduct.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Product');", true);
                    ddlProduct.Focus();
                    return;
                }

                Label lblProduct = (Label)row.FindControl("lblProduct");
                lblProduct.Text = ddlProduct.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlColor = (DropDownList)row.FindControl("ddlColor");
                if (ddlColor.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a Color');", true);
                    ddlColor.Focus();
                    return;
                }

                Label lblColor = (Label)row.FindControl("lblColor");
                lblColor.Text = ddlColor.SelectedValue;
                SetItem(row);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void ddlWhs_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                DropDownList ddlWhs = (DropDownList)row.FindControl("ddlWhs");
                if (ddlWhs.SelectedValue.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls selection a warehouse');", true);
                    ddlWhs.Focus();
                    return;
                }

                HiddenField hdnWhsCode = (HiddenField)row.FindControl("hdnWhsCode");
                if (hdnWhsCode != null && !string.IsNullOrEmpty(hdnWhsCode.Value))
                {
                    hdnWhsCode.Value = ddlWhs.SelectedValue;
                    DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
                    Label lblNo = (Label)row.FindControl("lblNo");
                    DataRow[] rowUpdate = tblIGN1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length > 0) rowUpdate[0]["WhsCode"] = hdnWhsCode.Value;
                    BindData(tblIGN1);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void SetItem(GridViewRow row)
        {
            DataTable tblIGN1 = (DataTable)Session["IGN1Table"];
            Label lblNo = (Label)row.FindControl("lblNo");
            DropDownList ddlModel = (DropDownList)row.FindControl("ddlModel");
            DropDownList ddlProduct = (DropDownList)row.FindControl("ddlProduct");
            DropDownList ddlCorlor = (DropDownList)row.FindControl("ddlColor");

            if (ddlModel != null && ddlProduct != null && ddlCorlor != null)
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                DataTable dtItem = GF.GetItem(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), ddlModel.SelectedValue, ddlProduct.SelectedValue, ddlCorlor.SelectedValue);
                //GetDefault defaultWS = new GetDefault();
                DataRow[] rowUpdate = null;
                if (dtItem != null && dtItem.Rows.Count == 1)
                {
                    rowUpdate = tblIGN1.Select("No=" + lblNo.Text);
                    if (rowUpdate.Length == 1)
                    {
                        rowUpdate[0]["ItemCode"] = dtItem.Rows[0]["ItemCode"].ToString();
                        rowUpdate[0]["Dscription"] = dtItem.Rows[0]["ItemName"].ToString();
                        rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                        rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                        rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                        rowUpdate[0]["Quantity"] = 1;
                        rowUpdate[0]["U_StockCountQty"] = 1;
                        rowUpdate[0]["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                    }
                }
                else
                {
                    rowUpdate = tblIGN1.Select("No=" + lblNo.Text);
                    rowUpdate[0]["ItemCode"] =
                    rowUpdate[0]["Dscription"] = string.Empty;
                    rowUpdate[0]["U_Model"] = ddlModel.SelectedValue;
                    rowUpdate[0]["U_Product"] = ddlProduct.SelectedValue;
                    rowUpdate[0]["U_Color"] = ddlCorlor.SelectedValue;
                    rowUpdate[0]["Quantity"] = 1;
                    rowUpdate[0]["U_StockCountQty"] = 1;
                    rowUpdate[0]["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;
                }
                BindData(tblIGN1);
            }
        }

        private DataTable datatable4Exp()
        {
            DataTable tblPDN1 = (DataTable)Session["IGN1Table"];

            DataTable dtRecords = new DataTable();
            dtRecords.Columns.Add(new DataColumn("Model"));
            dtRecords.Columns.Add(new DataColumn("Product"));
            dtRecords.Columns.Add(new DataColumn("Color"));
            dtRecords.Columns.Add(new DataColumn("Item"));
            dtRecords.Columns.Add(new DataColumn("VIN Number"));
            dtRecords.Columns.Add(new DataColumn("Engin Number"));
            DataRow dr = null;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            foreach (DataRow row in tblPDN1.Rows)
            {
                if (GF.GetItemGroupByCode(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(), row["ItemCode"].ToString()).Equals("104")) continue;
                string lsQty = row["Quantity"].ToString();
                int liQty = int.Parse(string.IsNullOrEmpty(lsQty) ? "0" : lsQty.Split('.')[0]);
                if (liQty == 1)
                {
                    dr = dtRecords.NewRow();
                    dr["Model"] = row["U_Model"];
                    dr["Product"] = row["U_Product"];
                    dr["Color"] = row["U_Color"];
                    dr["Item"] = row["ItemCode"];
                    dtRecords.Rows.Add(dr);
                }
                else if(liQty > 1)
                {
                    for (int i = 0; i < liQty; i++)
                    {
                        dr = dtRecords.NewRow();
                        dr["Model"] = row["U_Model"];
                        dr["Product"] = row["U_Product"];
                        dr["Color"] = row["U_Color"];
                        dr["Item"] = row["ItemCode"];
                        dtRecords.Rows.Add(dr);
                    }
                }
            }
            return dtRecords;
        }

        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tbIGN1 = (DataTable)Session["IGN1Table"];
            DataRow rowNew = tbIGN1.NewRow();
            rowNew["No"] = (tbIGN1.Rows.Count + 1).ToString();
            rowNew["ItemCode"] =
            rowNew["Dscription"] =
            rowNew["U_Model"] =
            rowNew["U_Product"] =
            rowNew["U_Color"] = string.Empty;
            rowNew["Quantity"] = 1;
            rowNew["U_StockCountQty"] = 1;
            rowNew["WhsCode"] = dtWhs.Rows.Count > 0 ? dtWhs.Rows[0]["WhsCode"].ToString() : string.Empty;

            tbIGN1.Rows.Add(rowNew);
            BindData(tbIGN1);
        }

        private bool ImportValidation()
        {

            if (this.FileUploadControl.PostedFile == null && this.FileUploadControl.PostedFile.FileName.Length <= 0)
            {
                Session["errorMessage"] = "Please select a Excel file before click on Import button.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            string lsFileExtension = Path.GetExtension(this.FileUploadControl.PostedFile.FileName);
            if (!lsFileExtension.Equals(".csv"))
            {
                Session["errorMessage"] = "Invalid file. Please select a .csv file.";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
                return false;
            }
            return true;
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            if (!ImportValidation()) return;
            // Reading .csv file
            string errMsg = GF.ReadFile(this.FileUploadControl.PostedFile.InputStream);
            if (string.IsNullOrEmpty(errMsg))
            {
                ImportData();
            }
            else
            {
                Session["errorMessage"] = errMsg;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + Session["errorMessage"].ToString() + "','');", true);
            }
        }

        private void ImportData()
        {
            DataTable tblSRNT = null;
            for (int x = 1; x < GF.FileLines.Count; x++)
            {
                string[] rowData = GF.FileLines[x].ToString().Split(',');
                BuildSRNT(ref tblSRNT, rowData[3], "", rowData[4], DateTime.Now.ToString("dd/MM/yyyy"), rowData[5], 1, "01", ConvertDocType.Get2String(DocType.GOODS_RECEIPT), "", "");
            }

            Session["tblSRNT"] = tblSRNT;           
        }

        protected void btnGetTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = datatable4Exp();

                if (dt != null)
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=GR.csv");
                    Response.ContentType = "text/csv";
                    int iColCount = dt.Columns.Count;

                    for (int i = 0; i < iColCount; i++)
                    {
                        Response.Write("\"" + dt.Columns[i] + "\"");
                        if (i < iColCount - 1)
                        {
                            Response.Write(",");
                        }
                    }

                    Response.Write(Environment.NewLine);
                    // Now write all the rows.
                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        for (int i = 0; i < iColCount; i++)
                        {
                            if (!Convert.IsDBNull(dt.Rows[x][i])) Response.Write("\"" + dt.Rows[x][i].ToString() + "\"");
                            if (i < iColCount - 1) Response.Write(",");
                        }
                        Response.Write(Environment.NewLine);
                    }
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

    }
}